import Taro, { Component, Config } from '@tarojs/taro'
import { Input, Image, View, ScrollView } from '@tarojs/components'
import './index.scss'
import classNames from 'classnames'
// import { APP_TABBAR_HEIGHT } from "@/config/config"
import { getCategoryList } from '@/api/categoryApi'
import { toSearchPage } from '@/utils/page_router'
import { Loading, TabBar } from '@/components/index'
import { TAB_BAR_HEIGHT } from "@/config/config"


export default class Index extends Component {
  state:any
  scrollTop:number
  config: Config = {
    backgroundTextStyle: "dark",
    navigationBarTitleText: '商品分类',
  }

  constructor() {
    super(...arguments)
    this.state = {
      loading: true,
      nodeKey: 0,
      dataList: [],
      nodeList: [],
    }
    this.scrollTop = -1
  }

  componentDidMount () {
    this.getList()
  }

  //  页面滚动触发事件的处理函数
  onPageScroll({ scrollTop }) {
    const { nodeKey, nodeList } = this.state

    //  防止点击节点的时候滚动问题
    if (this.scrollTop >= 0) {
      (scrollTop === this.scrollTop) && (this.scrollTop = -1)
      return
    }

    const list = nodeList.filter(i => (scrollTop >= i.top))
    const k = list.length - 1
    if (nodeKey !== k) {
      this.setState({
        nodeKey: k
      })
    }
  }

  //  获取分类数据
  getList() {
    getCategoryList().then(({ data }) => {
      const list = data.filter(i => i.child.length)

      this.setState({
        dataList: list
      }, () => {
        setTimeout(() => {
          this.getNodeLocation(list)
        })
      })
    })
  }

  //  获取节点位置
  getNodeLocation(list) {
    let height = 0
    const arr:any = []
    const query = Taro.createSelectorQuery()
    query.select(`#page-head`).boundingClientRect(res => {
      height = res.height
    })

    list.map((_i, k) => {
      query.select(`#cty-item-${k}`).boundingClientRect(({ top }) => {
        arr.push({ id: `#cty-item-${k}`, top: top - height })
      })
    })

    query.exec(() => {
      this.setState({
        nodeList: arr
      })
    })

    this.setState({
      loading: false
    })
  }

  //  切换类型
  onSwitchType(k) {
    const { nodeList } = this.state
    const top = nodeList[k]['top']
    this.setState({
      nodeKey: k
    }, () => {
      Taro.pageScrollTo({
        scrollTop: top,
        duration: 200,
      })
      this.scrollTop = top
    })
  }

  //  确定搜索
  onConfirmSearch(e) {
    toSearchPage({ name: e.detail.value })
  }

  //  点击分类
  onClickCategory(i) {
    toSearchPage({ cId: i.id, cName: i.name })
  }

  render () {
    const { loading, nodeKey, dataList } = this.state
    return (
      // @ts-ignore
      <View className='category-page xf-page'>
        {loading && <Loading />}
        <View id='page-head' className='page-head thin-border__b f-g-5'>
          <View className='input-box d-f a-i-c'>
            <View className='bnn-icon search-icon'>&#xe65c;</View>
            <Input
              className='search-input'
              confirmType='search'
              placeholder='点击搜索商品'
              placeholderClass='placeholder-input'
              onConfirm={this.onConfirmSearch.bind(this)}
            />
          </View>
        </View>
        <View className='page-body'>
          <ScrollView scrollY className='body-left cty-list'>
            {dataList.map((category, key) => {
              return (<View key={category.id} className={classNames('cty-item', {
                'cty-item__active': nodeKey === key
              })} onClick={this.onSwitchType.bind(this, key)}
              >{category.name}</View>)
            })}
          </ScrollView>
          <View className='body-right' style={{paddingBottom: `${TAB_BAR_HEIGHT}px`}}>
            {dataList.map((item, key) => {
              return (
                <View key={key} className={classNames('cty-item', {
                  'cty-item__last': key === dataList.length - 1
                })} id={`cty-item-${key}`}
                >
                  <View className='cty-name f-g-5'>{item.name}</View>
                  <View className='child-list d-f f-w-w'>
                    {item.child && item.child.map(c => {
                      return (<View key={c.id} className='child-item f-g-5 f-d-c' onClick={this.onClickCategory.bind(this, c)}>
                        <Image src={c.pic} className='child-img' />
                        <View className='child-name'>{c.name}</View>
                      </View>)
                    })}
                  </View>
                </View>
              )
            })}
          </View>
        </View>

        {/*<View style={{height: `${TAB_BAR_HEIGHT}px`}} />*/}
        <TabBar />
      </View>)
  }
}
